/**
 * 向设备发送指令
 * 1 读取配置信息
 * 2 读取所有记录
 * 3 ACK
 * 4 软件停止
 * 5 查询系统信息
 * @param {String/Number} cmd 指令 
 */

import { CRC16_1 } from '@/utils/crc'

let l1DataR = new Uint8Array(13)
let valL2 = new Uint8Array(5)
export default function(cmd, dataGet){
    l1DataR[0] = 0xCF
    l1DataR[1] = 0
    l1DataR[2] = 0
    l1DataR[3] = 5

    valL2[0] = 0x01
    valL2[1] = 0
    valL2[3] = 0
    valL2[4] = 0


    if(cmd == 1) {
        valL2[2] = 0x03
    }
    if(cmd == 2) {
        valL2[2] = 0x01
    }
    if(cmd == 4) {
        valL2[0] = 0x02
        valL2[1] = 0
        valL2[2] = 0x02
        valL2[3] = 0
        valL2[4] = 0
    }
    if(cmd == 5) {
        valL2[0] = 0x01
        valL2[1] = 0
        valL2[2] = 0x08
        valL2[3] = 0
        valL2[4] = 0
    }

    const crcValue = CRC16_1(valL2, 5)
    l1DataR[4] = ((crcValue & 0xFF00) >> 8)
    l1DataR[5] = ((crcValue & 0x00FF))
    l1DataR[6] = 0
    l1DataR[7] = 18

    if(cmd == 3) {
        l1DataR[1] = 0x10
        l1DataR[2] = 0
        l1DataR[3] = 0
        l1DataR[4] = 0
        l1DataR[5] = 0
        l1DataR[6] = dataGet[6]
        l1DataR[7] = dataGet[7]
    }

    if(cmd == 31) {
        l1DataR[0] = 0xAF
        l1DataR[1] = 0X10
        l1DataR[2] = 0
        l1DataR[3] = 0
        l1DataR[4] = 0
        l1DataR[5] = 0
        l1DataR[6] = dataGet[6]
        l1DataR[7] = dataGet[7]
    }

    let sendbuf = (cmd == 3 || cmd == 31) ?
        new Uint8Array(8) :
        new Uint8Array(13)
    
    sendbuf.set(l1DataR.subarray(0, 8), 0)
    if(sendbuf.length > 8) {
        sendbuf.set(valL2.subarray(0, 5), 8)
    }

    // console.log('指令' + cmd + ': ' + sendbuf)
    return sendbuf.buffer
}